import backtrader as bt
import pandas as pd
import datetime

class MyStrategy(bt.Strategy):
    def __init__(self):
        print("init")

    def start(self):
        print("The world call me!")

    def prenext(self):
        print("Not mature")

    def nextstart(self):
        print("Rites of passage")

    def next(self):
        print("a new bar")

        ma_value = sum(self.data.close[-cnt] for cnt in range(5))/5

        if self.data.close[0] > ma_value and self.data.close[-1] < ma_value:

            self.order = self.buy(size=10) # 买入10手

            print("long", self.data.datetime.datetime())
        if self.data.close[0] < ma_value and self.data.close[-1] > ma_value:
            self.order = self.sell(size=10) # 买入10手

    def stop(self):
        print("I should leave the world")


if __name__ == '__main__':
    cerebro = bt.Cerebro()
    dataframe = pd.read_csv("bitmex_data.csv")
    dataframe['open_time'] = pd.to_datetime(dataframe['open_time'])
    dataframe.set_index('open_time', inplace=True)
    dataframe['openinterest'] = 0
    brf_ = bt.feeds.PandasData(
        dataname=dataframe,
        fromdate=datetime.datetime(2020,10,19,4,24,00),
        todate=datetime.datetime(2020,10,19,12,43,00)
    )

    cerebro.adddata(brf_)
    cerebro.addstrategy(MyStrategy)

    cerebro.run()
    cerebro.plot()
